const validate = require('../../utils/validate')
const common = require('../../utils/common')
const { confirmDelivery } = require('../../services/order')
Page({
  data: {
    dataObj: {},
    activeTab: 1,
    orderId: '',
    deliveryCode: '',
    enable: true,
    tabList: [],
    dataList: [],
    currentStatus: '',
    submitText: '确认交货',
  },
  onLoad: function ({ data, id }) {
    if (!data) return
    this.setData({
      dataObj: JSON.parse(data),
      orderId: id
    }, () => {
      this.createTabs()
      this.createDataList()
    })
  },
  createTabs: function () {
    const { rzTime, sxTime } = this.data.dataObj
    const tabList = [{ name: rzTime, value: 1 }, { name: sxTime, value: 2 }]
    this.setData({
      tabList,
    })
  },
  onTabChange: function (e) {
    const { value } = e.currentTarget.dataset
    this.setData({
      activeTab: value
    }, this.createDataList)
  },
  createDataList: function () {
    const { rzVo, sxVo } = this.data.dataObj
    this.setData({
      dataList: this.data.activeTab == 1 ? rzVo.rzList : sxVo.sxList,
      currentStatus: this.data.activeTab == 1 ? rzVo.status : sxVo.status,
    }, this.canSubmit)
  },
  canSubmit: function () {
    const status = this.data.currentStatus
    let enable = false
    let submitText = '确认交货'
    if (status == 3) {
      enable = true
      submitText = '确认交货'
    } else if (status == 1 || status == 2) {
      enable = false
      submitText = '商品未到提货点，无法交货'
    } else {
      enable = false
      submitText = '交货成功'
    }
    this.setData({
      enable,
      submitText
    })
    return enable
  },
  getSkuIds: function () {
    return this.data.dataList.map(item => item.skuId)
  },

  onConfirm: function () {
    if (!this.data.enable) return
    // 订单确认提货
    const skuIds = this.getSkuIds()
    confirmDelivery({ orderId: this.data.orderId, skuIds }).then((res) => {
      common.showToast(res.message)
      // wx.navigateTo({ url: `/pages/delivery-product/index?data=${JSON.stringify(res.data)}` })
    }).catch(err => {
      common.log(err)
    })
  }
})
